package com.jingdianjichi.subject.domin.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jingdianjichi.subject.common.enums.IsDeletedFlagEnum;
import com.jingdianjichi.subject.domin.convert.SubjectCategoryConverter;
import com.jingdianjichi.subject.domin.convert.SubjectLabelConverter;
import com.jingdianjichi.subject.domin.entity.SubjectCategoryBO;
import com.jingdianjichi.subject.domin.entity.SubjectLabelBO;
import com.jingdianjichi.subject.domin.service.SubjectCategoryDomainService;
import com.jingdianjichi.subject.domin.utils.CacheUtil;
import com.jingdianjichi.subject.infra.basic.entity.SubjectCategory;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLabel;
import com.jingdianjichi.subject.infra.basic.entity.SubjectMapping;
import com.jingdianjichi.subject.infra.basic.service.SubjectCategoryService;
import com.jingdianjichi.subject.infra.basic.service.SubjectMappingService;
import com.jingdianjichi.subject.infra.basic.service.impl.SubjectLabelServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.security.auth.AuthPermission;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 86156
 * @version 1.0
 * @date 2024-10-02 10:55
 */
@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Autowired
    private SubjectLabelServiceImpl subjectLabelService;
    @Resource
    private ThreadPoolExecutor labelThreadPool;
    @Resource
    private CacheUtil<SubjectCategoryBO> cacheUtil;

    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryServiceImpl.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.instance.
                convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    @Override
    public List<SubjectCategoryBO> queryPrimaryCategory() {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(0L);
        List<SubjectCategory> categoryList = subjectCategoryService.queryPrimaryList(subjectCategory);
        List<SubjectCategoryBO> boList = SubjectCategoryConverter.instance.
                convertCategoryListToBoList(categoryList);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryServiceImpl.queryPrimaryCategory.bo:{}", JSON.toJSONString(boList));
        }
        return boList;
    }

    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.instance.
                convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        List<SubjectCategory> categoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOS = SubjectCategoryConverter.instance.
                convertCategoryListToBoList(categoryList);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryServiceImpl.queryPrimaryCategory.bo:{}", JSON.toJSONString(subjectCategoryBOS));
        }

        // 根据分类id查询题目数量
        subjectCategoryBOS.forEach(bo->{
            Integer subjectCount = subjectCategoryService.queryCountById(bo.getId());
            bo.setCount(subjectCount);
        });
        return subjectCategoryBOS;
    }

    /**
     * 更新分类
     * @param subjectCategoryBO
     * @return
     */
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.instance.
                convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count>0;
    }

    /**
     * 删除分类
     * @param subjectCategoryBO
     * @return
     */
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.instance.
                convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count>0;
    }

    /**
     * 根据分类id查询分类和标签信息集合
     * @param subjectCategoryBO
     * @return
     */
    @Override
    @SneakyThrows
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel."+id;
        List<SubjectCategoryBO> result = cacheUtil.getResult(cacheKey, SubjectCategoryBO.class,
                (key) -> getSubjectCategoryBOS(id));
        return result;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        // 根据分类查询子分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> categoryList = subjectCategoryService.queryCategory(subjectCategory);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryServiceImpl.queryCategoryAndLabel.categoryList:{}", categoryList);
        }
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.instance.convertCategoryListToBoList(categoryList);

        // 多线程的第二种实现方式
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutures = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getBoList(category),labelThreadPool)
        ).collect(Collectors.toList());

        completableFutures.forEach(future->{
            try {
                Map<Long, List<SubjectLabelBO>> resultMap = future.get();
                if(!MapUtils.isEmpty(resultMap)){
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        categoryBOList.forEach(category->{
            category.setLabelBOList(map.get(category.getId()));
        });

        return categoryBOList;
    }


    /**
     * 一次性获取标签信息 - 抽取
     * @param categoryBO
     * @return
     */
    private Map<Long,List<SubjectLabelBO>> getBoList(SubjectCategoryBO categoryBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryServiceImpl.getBoList.BO:{}", JSON.toJSONString(categoryBO));
        }
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(categoryBO.getId());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if(CollectionUtils.isEmpty(mappingList)){
            return null;
        }
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).
                collect(Collectors.toList());
        List<SubjectLabel> labels = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        for (SubjectLabel label : labels) {
            SubjectLabelBO subjectLabelBO = SubjectLabelConverter.instance.convertEntityToBo(label);
            labelBOList.add(subjectLabelBO);
        }
        map.put(categoryBO.getId(),labelBOList);
        return map;
    }

}


/*

         // 构建线程任务集合
        List<FutureTask<Map<Long,List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
        categoryBOList.forEach(categoryBO->{
            // 构建任务
            FutureTask<Map<Long,List<SubjectLabelBO>>> futureTask = new FutureTask<>(()->
                    getBoList(categoryBO));
            futureTaskList.add(futureTask);
            // 往线程池中提交任务
            labelThreadPool.submit(futureTask);
        });

        // 遍历任务返回值,封装返回结果
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        for (FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask : futureTaskList) {
            Map<Long, List<SubjectLabelBO>> resultMap = futureTask.get();
            if(CollectionUtils.isEmpty(resultMap)){
                continue;
            }
            map.putAll(resultMap);
        }

        categoryBOList.forEach(category->{
            category.setBoList(map.get(category.getId()));
        });



         // 多线程的第二种实现方式
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutures = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getBoList(category),labelThreadPool)
        ).collect(Collectors.toList());

        completableFutures.forEach(future->{
            try {
                Map<Long, List<SubjectLabelBO>> resultMap = future.get();
                map.putAll(resultMap);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });


* */
